package utils;

import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import jakarta.json.stream.JsonGenerator;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class EsUtils {

    private static final JacksonJsonpMapper JACKSON_JSONP_MAPPER = new JacksonJsonpMapper();

    /**
     * SearchRequest转DSL
     *
     * @param searchRequest
     */
    public static void printSearchRequestDSL(SearchRequest searchRequest) {
        ByteArrayOutputStream dsl;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             JsonGenerator generator = JACKSON_JSONP_MAPPER.jsonProvider().createGenerator(byteArrayOutputStream)) {
            searchRequest.serialize(generator, JACKSON_JSONP_MAPPER);
            dsl = byteArrayOutputStream;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        try {
            dsl.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(dsl);
    }

    /**
     * Query转DSL
     *
     * @param query
     */
    public static void printSearchRequestDSL(Query query) {
        ByteArrayOutputStream dsl;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             JsonGenerator generator = JACKSON_JSONP_MAPPER.jsonProvider().createGenerator(byteArrayOutputStream)) {
            query.serialize(generator, JACKSON_JSONP_MAPPER);
            dsl = byteArrayOutputStream;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        try {
            dsl.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(dsl);
    }
}
